package com.jadeen.common.interceptor.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jadeen.common.domain.AjaxResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Jadeen
 * @date: 2025/8/28 20:20
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 预处理方法，在请求处理前被调用
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器
     * @return true表示放行，false表示拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("当前会话是否登录：" + StpUtil.isLogin());
        boolean login = StpUtil.isLogin();
        if (!login) {
            // 未登录时返回401状态码
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("code", 401);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(ajaxResult);
            response.getWriter().write(jsonString);
            return false;
        }
        return true;
    }
}
